﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web.UI.HtmlControls;

public partial class Main_Inventory_DCOutward : System.Web.UI.Page
{
    Datautility du = new Datautility();
    int dcounter = 2;
    string sql = "";
    List<string> Listdcounter;
    List<string> ListItem;
    List<string> ListUom;
    List<string> ListUomId;
    List<string> ListQty;
    List<string> ListBtnQty;
    List<string> ListHidLocationBillLevel;
    List<string> ListRate;
    List<string> ListAmount;
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        OverrideAddMore(); 
    }    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            //ScriptManager.RegisterStartupScript(Page, this.GetType(), "redirect", "window.open('../../login.aspx','_parent');", true);
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (Request.QueryString["action"] != null)
        {
            if (Request.QueryString["action"].ToString() == "addnew")
            {
                PnlAddNew.Visible = true;

                if (!IsPostBack)
                {

                    Listdcounter = new List<string>();
                    ViewState["Listdcounter"] = Listdcounter;

                    ListItem = new List<string>();
                    ViewState["ListItem"] = ListItem;

                    ListUom = new List<string>();
                    ViewState["ListUom"] = ListUom;

                    ListUomId = new List<string>();
                    ViewState["ListUomId"] = ListUomId;

                    ListQty = new List<string>();
                    ViewState["ListQty"] = ListQty;

                    ListBtnQty = new List<string>();
                    ViewState["ListBtnQty"] = ListBtnQty;

                    ListHidLocationBillLevel = new List<string>();
                    ViewState["ListHidLocationBillLevel"] = ListHidLocationBillLevel;

                    ListRate = new List<string>();
                    ViewState["ListRate"] = ListRate;

                    ListAmount = new List<string>();
                    ViewState["ListAmount"] = ListAmount;

                    Bindddldcformat();
                    binditem(ddlitems1);
                    binditem(ddlitems2);
                    bindtaxgroup();
                    Bindcategory();
                    BindCustomer();

                }
                if (Request.QueryString["msg"] != null)
                {
                    if (Request.QueryString["msg"].ToString() == "true")
                    {
                        lblMsg.Text = "Dc Outward Created";
                    }
                }
            }
            else if (Request.QueryString["action"].ToString() == "view")
            {
                if (!IsPostBack)
                {
                    PnlView.Visible = true;
                    Bindgridview();
                }
            }
        }

        
    }

    protected void AddMoreRow() //Html Rows
    {
        dcounter++;
       
        HtmlTableRow row1 = new HtmlTableRow();
        HtmlTableCell cell1 = new HtmlTableCell();
        cell1.Align = "Center";
        DropDownList ddl = new DropDownList();
        ddl.ID = "ddlitems" + dcounter.ToString();
        ddl.CssClass = "dropdown";
        ddl.Width = Unit.Percentage(95);
        binditem(ddl);
        ddl.AutoPostBack = true;
        ddl.SelectedIndexChanged += new EventHandler(ddlitems_OnSelectedIndexChanged);
        cell1.Controls.Add(ddl);
        Listdcounter.Add(dcounter.ToString());
        ListItem.Add(ddl.ID);
        

        HtmlTableCell cell2 = new HtmlTableCell();
        cell2.Align = "Center";
        TextBox txtunit = new TextBox();
        txtunit.ID = "txtunit" + dcounter.ToString();
        txtunit.Width = Unit.Percentage(95);
        txtunit.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtunit.CssClass = "input";
        HiddenField huomid = new HiddenField();
        huomid.ID = "huomid" + dcounter.ToString();
        cell2.Controls.Add(txtunit);
        cell2.Controls.Add(huomid);
        ListUom.Add(txtunit.ID);
        ListUomId.Add(huomid.ID);

        HtmlTableCell cell3 = new HtmlTableCell();
        cell3.Align = "Center";
        TextBox txtquantity = new TextBox();
        txtquantity.ID = "txtquantity" + dcounter.ToString();
        txtquantity.Width = Unit.Percentage(88);
        txtquantity.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtquantity.Attributes.Add("Onblur", "return CalculateAmtQtyRate();");
        txtquantity.CssClass = "inputnumber";
        Label lblspace = new Label();
        lblspace.Text = "&nbsp;";
        cell3.Controls.Add(txtquantity);
        cell3.Controls.Add(lblspace);
        ListQty.Add(txtquantity.ID);

        Button btnQtyBillLevel = new Button();
        btnQtyBillLevel.ID = "btnQtyBillLevel" + dcounter.ToString();
        btnQtyBillLevel.CssClass = "button";
        btnQtyBillLevel.Width = Unit.Percentage(5);
        btnQtyBillLevel.Text = "...";
        HiddenField hidLocationBillLevel = new HiddenField();
        hidLocationBillLevel.ID = "hidLocationBillLevel" + dcounter.ToString();
        cell3.Controls.Add(btnQtyBillLevel);
        cell3.Controls.Add(hidLocationBillLevel);
        ListBtnQty.Add(btnQtyBillLevel.ID);
        ListHidLocationBillLevel.Add(hidLocationBillLevel.ID);

        HtmlTableCell cell4 = new HtmlTableCell();
        cell4.Align = "Center";
        TextBox txtrate = new TextBox();
        txtrate.ID = "txtrate" + dcounter.ToString();
        txtrate.Width = Unit.Percentage(95);
       // txtrate.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtrate.Attributes.Add("Onblur", "return CalculateAmtQtyRate();");
        txtrate.CssClass = "inputnumber";
        cell4.Controls.Add(txtrate);
        ListRate.Add(txtrate.ID);

        HtmlTableCell cell5 = new HtmlTableCell();
        cell5.Align = "Center";
        TextBox txtamount = new TextBox();
        txtamount.ID = "txtamount" + dcounter.ToString();
        txtamount.Width = Unit.Percentage(95);
        txtamount.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtamount.CssClass = "inputnumber";
        cell5.Controls.Add(txtamount);
        ListAmount.Add(txtamount.ID);

        row1.Cells.Add(cell1);
        row1.Cells.Add(cell2);
        row1.Cells.Add(cell3);
        row1.Cells.Add(cell4);
        row1.Cells.Add(cell5);

        tblitem.Rows.Add(row1);
        hcount.Value = dcounter.ToString();

        ViewState["Listdcounter"] = Listdcounter;
        ViewState["ListItem"] = ListItem;
        ViewState["ListUom"] = ListUom;
        ViewState["ListUomId"] = ListUomId;
        ViewState["ListQty"] = ListQty;
        ViewState["ListBtnQty"] = ListBtnQty;
        ViewState["ListHidLocationBillLevel"] = ListHidLocationBillLevel;
        ViewState["ListRate"] = ListRate;
        ViewState["ListAmount"] = ListAmount;
       

    } 
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        AddMoreRow();
        BindJavaScriptBillLevel();
    }
    protected void OverrideAddMore()
    {
        Listdcounter = (List<string>)ViewState["Listdcounter"];
        ListItem = (List<string>)ViewState["ListItem"];
        ListUom = (List<string>)ViewState["ListUom"];
        ListUomId = (List<string>)ViewState["ListUomId"];
        ListQty = (List<string>)ViewState["ListQty"];
        ListBtnQty = (List<string>)ViewState["ListBtnQty"];
        ListHidLocationBillLevel = (List<string>)ViewState["ListHidLocationBillLevel"];
        ListRate = (List<string>)ViewState["ListRate"];
        ListAmount = (List<string>)ViewState["ListAmount"];
        
        if (Listdcounter != null)
        {
            int temdcounter = Convert.ToInt32(Listdcounter.Count.ToString());            
            for (int i = 0; i < temdcounter; i++)
            {
                dcounter++;

                HtmlTableRow row1 = new HtmlTableRow();
                HtmlTableCell cell1 = new HtmlTableCell();
                cell1.Align = "Center";
                DropDownList ddl = new DropDownList();
                ddl.ID = ListItem[i].ToString();
                ddl.CssClass = "dropdown";
                ddl.Width = Unit.Percentage(95);
                binditem(ddl);
                ddl.AutoPostBack = true;
                ddl.SelectedIndexChanged += new EventHandler(ddlitems_OnSelectedIndexChanged);
                cell1.Controls.Add(ddl);

                HtmlTableCell cell2 = new HtmlTableCell();
                cell2.Align = "Center";
                TextBox txtunit = new TextBox();
                txtunit.ID = ListUom[i].ToString();
                txtunit.Width = Unit.Percentage(95);
                txtunit.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtunit.CssClass = "input";
                HiddenField huomid = new HiddenField();
                huomid.ID = ListUomId[i].ToString();
                cell2.Controls.Add(txtunit);
                cell2.Controls.Add(huomid);


                HtmlTableCell cell3 = new HtmlTableCell();
                cell3.Align = "Center";
                TextBox txtquantity = new TextBox();
                txtquantity.ID = ListQty[i].ToString();
                txtquantity.Width = Unit.Percentage(88);
                txtquantity.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtquantity.Attributes.Add("Onblur", "return CalculateAmtQtyRate();");
                txtquantity.CssClass = "inputnumber";
                Label lblspace = new Label();
                lblspace.Text = "&nbsp;";
                cell3.Controls.Add(txtquantity);
                cell3.Controls.Add(lblspace);


                Button btnQtyBillLevel = new Button();
                btnQtyBillLevel.ID = ListBtnQty[i].ToString();
                btnQtyBillLevel.CssClass = "button";
                btnQtyBillLevel.Width = Unit.Percentage(5);
                btnQtyBillLevel.Text = "...";
                HiddenField hidLocationBillLevel = new HiddenField();
                hidLocationBillLevel.ID = ListHidLocationBillLevel[i].ToString();
                cell3.Controls.Add(btnQtyBillLevel);
                cell3.Controls.Add(hidLocationBillLevel);


                HtmlTableCell cell4 = new HtmlTableCell();
                cell4.Align = "Center";
                TextBox txtrate = new TextBox();
                txtrate.ID = ListRate[i].ToString();
                txtrate.Width = Unit.Percentage(95);
               // txtrate.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtrate.Attributes.Add("Onblur", "return CalculateAmtQtyRate();");
                txtrate.CssClass = "inputnumber";
                cell4.Controls.Add(txtrate);

                HtmlTableCell cell5 = new HtmlTableCell();
                cell5.Align = "Center";
                TextBox txtamount = new TextBox();
                txtamount.ID = ListAmount[i].ToString();
                txtamount.Width = Unit.Percentage(95);
                txtamount.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtamount.CssClass = "inputnumber";
                cell5.Controls.Add(txtamount);

                row1.Cells.Add(cell1);
                row1.Cells.Add(cell2);
                row1.Cells.Add(cell3);
                row1.Cells.Add(cell4);
                row1.Cells.Add(cell5);

                tblitem.Rows.Add(row1);
            }
        }
    }
    
    protected void binditem(DropDownList ddl)
    {
        SqlParameter[] sparam ={
                                   new SqlParameter("@TFOID",ddldcformat.SelectedValue)
                               };
        DataTable dtitem = du.getdatausingprocedure("USP_IVR_GetItemForPurchaseInvoice", sparam);
        if (dtitem.Rows.Count > 0)
        {
            ddl.DataSource = dtitem;
            ddl.DataTextField = "ITMNAME";
            ddl.DataValueField = "ITMID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("-Select Items-", "0"));
        }
        else
        {
            ddl.Items.Clear();
        }
    }  //Function for binding item in Dropropdown
    protected void ddlitems_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        string ddlid = ddl.ID.ToString().Substring(8);
        int rowno = Convert.ToInt32(ddlid.ToString());
        TextBox txtunit = (TextBox)tblitem.Rows[rowno].FindControl("txtunit" + rowno.ToString());
        HiddenField huono = (HiddenField)tblitem.Rows[rowno].FindControl("huomid" + rowno.ToString());

        SqlParameter[] parr = { 
                              new SqlParameter("@itemid",ddl.SelectedValue)
                              };
        DataTable dt = du.getdatausingprocedure("usp_ivr_get_uom_by_itemid", parr);
        if (dt.Rows.Count > 0)
        {
            txtunit.Text = dt.Rows[0]["UOMNAME"].ToString();
            huono.Value = dt.Rows[0]["UOMID"].ToString();
        }
        BindJavaScriptBillLevel();
    }

    protected void Bindddldcformat()//Function for binding DCFormate Dropropdown
    {
        SqlParameter[] parr = {
                                  new SqlParameter("@TranType","2")
                              };
        DataTable dtformatname = du.getdatausingprocedure("USP_IVR_GetTransactionFormat" ,parr);
        if (dtformatname.Rows.Count > 0)
        {
            ddldcformat.DataSource = dtformatname;
            ddldcformat.DataTextField = "FormatName";
            ddldcformat.DataValueField = "Tfoid";
            ddldcformat.DataBind();
            ddldcformat.SelectedIndex = 0;
            Bind_VoucherNo();
        }
    } 
    protected void Bind_VoucherNo()
    {
        if (ddldcformat.SelectedValue != "0")
        {
            SqlParameter[] sparam =
                                 {
                                     new SqlParameter("@TFOID",ddldcformat.SelectedValue),
                                     new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                 };
            DataTable DTNum = du.getdatausingprocedure("USP_IVR_GetMaxVoucherNumber", sparam);
            if (DTNum.Rows.Count > 0)
            {

                txtPrefix.Text = DTNum.Rows[0]["NUMPREFIX"].ToString();
                txtVoucher.Text = DTNum.Rows[0]["NUMSTART"].ToString();
                txtSuffix.Text = DTNum.Rows[0]["NUMSUFFIX"].ToString();
            }
        }
    }
    protected void bindtaxgroup()
    {
        SqlParameter[] parr = {
                                  new SqlParameter("@ISDCIN","0")
                              };
        DataTable dttaxgroup = du.getdatausingprocedure("USP_IVR_GetDCGroup", parr);
        if (dttaxgroup.Rows.Count > 0)
        {
            DdlTax.DataSource = dttaxgroup;
            DdlTax.DataTextField =  "Subclass";
            DdlTax.DataValueField = "Id";
            DdlTax.DataBind();
            DdlTax.Items.Insert(0, new ListItem("-Tax Group-", "0")); 
        }
    }
    protected void BindCustomer()
    {
            DataTable dtCustomer = du.getdatausingprocedure("USP_ACC_GetLedgerForPurchaseInvoice");
            if (dtCustomer.Rows.Count > 0)
            {
                DdlCustomer.DataSource = dtCustomer;
                DdlCustomer.DataTextField = "LNAME";
                DdlCustomer.DataValueField = "LID";
                DdlCustomer.DataBind();
                DdlCustomer.Items.Insert(0, new ListItem("-Select Customer-", "0"));
            }
    }

    protected void Bindcategory()//Function for binding Category Dropropdown
    {
        DataTable dtcategory = du.getdatausingprocedure("USP_IVR_GetDCCategory");
        if (dtcategory.Rows.Count > 0)
        {
            DdlCategory.DataSource = dtcategory;
            DdlCategory.DataTextField = "CATEGORYNAME";
            DdlCategory.DataValueField = "CATEGORYCODE";
            DdlCategory.DataBind();
            DdlCategory.Items.Insert(0, new ListItem("-Select Category-", "0"));
        }
    }
    protected void binduom(string itemid, int rowno)
    {
        if (itemid.ToString() != string.Empty)
        {
            SqlParameter[] parr = { 
                                    new SqlParameter("@itemid",itemid)
                                  };
            DataTable dt = du.getdatausingprocedure("usp_ivr_get_uom_by_itemid", parr);
            if (dt.Rows.Count > 0)
            {
                TextBox txtunit = (TextBox)tblitem.Rows[rowno].FindControl("txtunit" + rowno.ToString());
                HiddenField huono = (HiddenField)tblitem.Rows[rowno].FindControl("huomid" + rowno.ToString());
                txtunit.Text = dt.Rows[0]["UOMNAME"].ToString();
                huono.Value = dt.Rows[0]["UOMID"].ToString();

            }
        }
    }
    protected void ddldcformat_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            Bind_VoucherNo();
            CheckTranFormate();
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void BindJavaScriptBillLevel()//A common function for add javascript attribute to btn quantity
    {
        int intCount = Convert.ToInt32(hcount.Value);
        for (int i = 1; i <= intCount; i++)
        {
            DropDownList ddlitems = (DropDownList)tblitem.Rows[i].FindControl("ddlitems" + i.ToString());
            TextBox txtquantity = (TextBox)tblitem.Rows[i].FindControl("txtquantity" + i.ToString());
            HiddenField hidLocationBillLevel = (HiddenField)tblitem.Rows[i].FindControl("hidLocationBillLevel" + i.ToString());
            Button btnQtyBillLevel = (Button)tblitem.Rows[i].FindControl("btnQtyBillLevel" + i.ToString());
            btnQtyBillLevel.Attributes.Add("onclick", "return GetQuantity('" + ddlitems.SelectedValue + "', '" + txtquantity.ClientID.ToString() + "', '" + hidLocationBillLevel.ClientID.ToString() + "');");
        }
    }
    protected void CheckTranFormate()//disabled delivery details and other details on the basis of DC format
    {
        EmptyTextBoxes(OtherDetails);
        EmptyTextBoxes(DeliveryDetails); 
        if (ddldcformat.SelectedValue != "0")
        {
            DataTable dtpermission = du.getdata("select * from IVR_TRANFORMAT where tfoid=" + ddldcformat.SelectedValue + "");
            if (dtpermission.Rows.Count > 0)
            {
                if (dtpermission.Rows[0]["DELIVERYDETAILS"].ToString() == "False")
                {
                    //divdeliverydetails.Disabled = true;
                    txtmodeofdelivery.Enabled = false;
                    txtfreightindicator.Enabled = false;
                    txttransportername.Enabled = false;
                    txtdocumentno.Enabled = false;
                    txtdeliverydate.Enabled = false;
                    txtvehicleno.Enabled = false;
                    btnimage.Enabled = false;
                    CalendarExtender1.Enabled = false;
                    //spanRequireDate.Visible = false;
                    //hidCheckDelivery.Value = "False";
                }
                else
                {
                    //divdeliverydetails.Disabled = false;
                    txtmodeofdelivery.Enabled = true;
                    txtfreightindicator.Enabled = true;
                    txttransportername.Enabled = true;
                    txtdocumentno.Enabled = true;
                    txtdeliverydate.Enabled = true;
                    txtvehicleno.Enabled = true;
                    btnimage.Enabled = true;
                    CalendarExtender1.Enabled = true;
                    //spanRequireDate.Visible = true;
                   // hidCheckDelivery.Value = "True";
                }

                if (dtpermission.Rows[0]["PREPAREDBY"].ToString() == "True")
                {
                    txtpreparedby.Enabled = true;
                }
                else
                {
                    txtpreparedby.Enabled = false;
                }
                if (dtpermission.Rows[0]["CHECKEDBY"].ToString() == "True")
                {
                    txtcheckedby.Enabled = true;
                }
                else
                {
                    txtcheckedby.Enabled = false;
                }
                if (dtpermission.Rows[0]["AUTHSIGNATORY"].ToString() == "True")
                {
                    txtauthorisedsignature.Enabled = true;
                }
                else
                {
                    txtauthorisedsignature.Enabled = false;
                }
                if (dtpermission.Rows[0]["NOTE"].ToString() == "True")
                {
                    txtnote.Enabled = true;
                }
                else
                {
                    txtnote.Enabled = false;
                }
                if (dtpermission.Rows[0]["REMARKS"].ToString() == "True")
                {
                    txtremarks.Enabled = true;
                }
                else
                {
                    txtremarks.Enabled = false;
                }
            }
        }
    }


    protected void BindMain()
    {
        string strTransDate = string.Format("{0:MM/dd/yyyy}", System.DateTime.Now).ToString();

        if (txtdate.Text.ToString() != string.Empty)
        {
            string[] str1 = txtdate.Text.ToString().Split('/');
            strTransDate = str1[1].ToString() + "/" + str1[0].ToString() + "/" + str1[2].ToString();
        }
        SqlParameter[] sparam ={
                                new SqlParameter("@TRANTYPEID","2"),
                                new SqlParameter("@FINYEAR", Session["FINYEAR"].ToString()),
                                new SqlParameter("@TFOID", ddldcformat.SelectedValue),
                                new SqlParameter("@TRNNUM", txtVoucher.Text.Trim()),
                                new SqlParameter("@TRNDATE",strTransDate),
                                new SqlParameter("@VENDCUST_LID",DdlCustomer.SelectedValue ),
                                new SqlParameter("@TAX_MAINCLASSID", "0"),
                                new SqlParameter("@TRNSTATUS","1"),
                                new SqlParameter("@SHIPTO_VSTID", hidDeliveryId.Value),
                                new SqlParameter("@MODEOFPAY","0"),
                                new SqlParameter("@CREDITPERIOD","0"),
                                new SqlParameter("@DCTAX_SUBCLASSID",DdlTax.SelectedValue),
                                new SqlParameter("@DC_CATEGORYCODE",DdlCategory.SelectedValue),
                                new SqlParameter("@CNAME", Session["username"].ToString())
                               };

        int Main = du.executeprocedure("USP_IVR_SaveTranMain", sparam);
        lblMsg.Text = "DC Outward Created";
        if (Main > 0)
        {
            string sql = "Select Ident_Current('IVR_TRAN_MAIN') as TranId";
            DataTable DTTranid = du.getdata(sql);
            if (DTTranid.Rows.Count > 0)
            {
                InsertItemTranItem(DTTranid.Rows[0]["TranId"].ToString());
                BindOthDetail(DTTranid.Rows[0]["TranId"].ToString());
                BindDileveryDetails(DTTranid.Rows[0]["TranId"].ToString());
                Response.Redirect("DCOutward.aspx?action=view");
                lblMsg.Text = "DC Outward Created";
            }
        }
    }
    protected void InsertItemTranItem(string strTranId)  //get qty
    {
        if (strTranId.ToString() != string.Empty)
        {
            int intResult = 0;
            int intCount = Convert.ToInt32(hcount.Value);
            for (int i = 1; i <= intCount; i++)
            {
                DropDownList ddlItem = (DropDownList)tblitem.Rows[i].FindControl("ddlitems" + i.ToString());
                HiddenField hidunitId = (HiddenField)tblitem.Rows[i].FindControl("huomid" + i.ToString());
                TextBox txtQuantity = (TextBox)tblitem.Rows[i].FindControl("txtquantity" + i.ToString());
                TextBox txtRate = (TextBox)tblitem.Rows[i].FindControl("txtrate" + i.ToString());
                TextBox txtAmount = (TextBox)tblitem.Rows[i].FindControl("txtamount" + i.ToString());                
                if (txtQuantity.Text != string.Empty && txtRate.Text != string.Empty)
                {
                    double dblItemAmount = 0;
                    dblItemAmount = Convert.ToDouble(txtAmount.Text);

                    SqlParameter[] sparam ={
                                   new SqlParameter("@TRNID",strTranId.ToString()),
                                   new SqlParameter("@ITMID",ddlItem.SelectedValue ),
                                   new SqlParameter("@ITMQTY",txtQuantity.Text.Trim()),
                                   new SqlParameter("@UOMID",hidunitId.Value.ToString()),
                                   new SqlParameter("@RATE",txtRate.Text.Trim()),
                                   new SqlParameter("@GROSSAMT",txtAmount.Text.Trim()),
                                   new SqlParameter("@NETAMT",dblItemAmount),
                                   new SqlParameter("@TAX_TXMASID","0"),
                                   new SqlParameter("@TAXPER","0"),
                                   new SqlParameter("@TAXAMT","0"),
                                   new SqlParameter("@ITMAMT",dblItemAmount),
                                   new SqlParameter("@ITMPENDINGQTY",txtQuantity.Text.Trim()),                               
                               };
                    intResult = du.executeprocedure("USP_IVR_SaveTranItem", sparam);
                  
                }
                if (intResult > 0)
                {
                    string sql = "Select Ident_Current('IVR_TRAN_ITEM') as TITID";
                    DataTable DTTranid = du.getdata(sql);
                    if (DTTranid.Rows.Count > 0)
                    {
                        BindmainItemDetails(strTranId, DTTranid.Rows[0]["TITID"].ToString(), i);
                    }
                    intResult = 0;
                }
            }
        }
    }


    protected void BindmainItemDetails(string tranId, string tranItemId, int rowId)
    {
        if (tranId.ToString() != string.Empty && tranItemId.ToString() != string.Empty)
        {
            string strsql = "";
            string strTransDate = string.Empty;
            if (txtdate.Text.ToString() != string.Empty)
            {
                string[] str = txtdate.Text.ToString().Split('/');
                strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            DropDownList ddlItems = (DropDownList)tblitem.Rows[rowId].FindControl("ddlitems" + rowId.ToString());
            TextBox txtQuantity = (TextBox)tblitem.Rows[rowId].FindControl("txtquantity" + rowId.ToString());
            TextBox txtRate = (TextBox)tblitem.Rows[rowId].FindControl("txtrate" + rowId.ToString());
            HiddenField hidLocation = (HiddenField)tblitem.Rows[rowId].FindControl("hidLocationBillLevel" + rowId.ToString());

            if (txtQuantity.Text != string.Empty && txtRate.Text != string.Empty)
            {
                if (hidLocation.Value.ToString() != string.Empty)
                {
                    if (isBatchEnabled(ddlItems.SelectedValue) && isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        List<string> lstWarranty1 = new List<string>();
                        List<string> lstWarrantyDetails1 = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/") && hidLocation.Value.ToString().Contains("|") && hidLocation.Value.ToString().Contains(":"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                string[] str2 = str1[1].ToString().Split(':');
                                lstBatchId.Add(str2[0].ToString());
                                string[] str3 = str2[1].ToString().Split(';');
                                lstWarranty1.Add(str3[0].ToString());
                                lstWarrantyDetails1.Add(str3[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            string[] str2 = str1[1].ToString().Split(':');
                            lstBatchId.Add(str2[0].ToString());
                            string[] str3 = str2[1].ToString().Split(';');
                            lstWarranty1.Add(str3[0].ToString());
                            lstWarrantyDetails1.Add(str3[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY",lstWarranty1[j].ToString()),
                                                               new SqlParameter("@WARRANTYPERIOD",lstWarrantyDetails1[j].ToString())                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (isBatchEnabled(ddlItems.SelectedValue) && !isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/") && hidLocation.Value.ToString().Contains("|"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                lstBatchId.Add(str1[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            lstBatchId.Add(str1[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (!isBatchEnabled(ddlItems.SelectedValue) && !isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                lstLocationQty.Add(str[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            lstLocationQty.Add(str[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),                                                               
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID","0"),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    protected bool isBatchEnabled(string ItemId)//A common function for check item batch enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            string sql = "Select ITMBATCH from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = du.getdata(sql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }
    protected bool isWarrantyEnabled(string ItemId)//A common function for check item warranty enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            string sql = "Select ITMBATCH, ITMBATCHOPT from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = du.getdata(sql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0 && Convert.ToDouble(DT.Rows[0]["ITMBATCHOPT"]) == 1)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }
    protected void BindDileveryDetails(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            string strDeliveryDate = "1/1/1900";
            if (txtdeliverydate.Text != string.Empty)
            {
                string[] str = txtdeliverydate.Text.ToString().Split('/');
                strDeliveryDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            SqlParameter[] parm = { 
                                  new SqlParameter("@TRNID",tranId.ToString()),
                                  new SqlParameter("@MODEOFDELIVERY",txtmodeofdelivery.Text),
                                  new SqlParameter("@DELIVERYDATE",strDeliveryDate),
                                  new SqlParameter("@DOCUMENTNUM",txtdocumentno.Text),
                                  new SqlParameter("@VEHICLENUM",txtvehicleno.Text),
                                  new SqlParameter("@FREIGHTINDICATOR",txtfreightindicator.Text),
                                  new SqlParameter("@TRANSPORTNAME",txttransportername.Text)
                              };
            int result = du.executeprocedure("USP_IVR_SaveTranDelivery", parm);
        }
    }
    protected void BindOthDetail(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            SqlParameter[] parm = {
                                  new SqlParameter("@TRNID",tranId.ToString()),
                                  new SqlParameter("@PREPAREDBY",txtpreparedby.Text.Trim()),
                                  new SqlParameter("@CHECKEDBY",txtcheckedby.Text.Trim()),
                                  new SqlParameter("@AUTHRSDSIGNAT",txtauthorisedsignature.Text.Trim()),
                                  new SqlParameter("@REMARKS",txtremarks.Text.Trim()),
                              };
            du.executeprocedure("USP_IVR_SaveTranOthers", parm);
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        BindMain();
    }

    protected void DdlCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDeliveryAdd();
    }
    protected void bindDeliveryAdd() //Bind Delivery Address on the basis of dropdown selected value
    {
        
        SqlParameter[] parrr = { 
                                 new SqlParameter("@ledid",DdlCustomer.SelectedValue)
                               };
        DataTable dtdeladd = du.getdatausingprocedure("usp_get_deliveryadd_by_ledid", parrr);
        if (dtdeladd.Rows.Count > 0)
        {
            hidDeliveryId.Value = dtdeladd.Rows[0]["deliveryaddid"].ToString();
            StringBuilder sb = new StringBuilder();
            sb.Append(dtdeladd.Rows[0]["Title"].ToString() + " , ");
            sb.Append(dtdeladd.Rows[0]["contactname"].ToString() + "\n");
            sb.Append(dtdeladd.Rows[0]["add1"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["add2"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["add3"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["pincode"].ToString() + "\n  ");
            sb.Append(dtdeladd.Rows[0]["state"].ToString() + "\n  ");
            sb.Append(dtdeladd.Rows[0]["country"].ToString() + " ");

            TxtDeliveryAddress.Text = sb.ToString();
        }
        else
        {
            TxtDeliveryAddress.Text = string.Empty;
        }
    }

    protected void Bindgridview()//Binding data in grid view
    {
        
        DataTable dt = du.getdatausingprocedure("usp_ivr_displayDCOutward");
        if (dt.Rows.Count > 0)
        {
            //lblMsg.Text = dt.Rows.Count.ToString();
          
            DataView dv = dt.DefaultView;
            dv.Sort = "TRNDATE desc";
            Grdoutward.DataSource =dv;
            Grdoutward.DataBind();
        }
    }

    protected void Grdoutward_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Grdoutward.PageIndex = e.NewPageIndex;
        Bindgridview();
    }
    protected void Grdoutward_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string formateid = Grdoutward.DataKeys[e.Row.RowIndex].Values[0].ToString();
            //string supplierid = grdview.DataKeys[e.Row.RowIndex].Values[1].ToString();
            string trnid = Grdoutward.DataKeys[e.Row.RowIndex].Values[5].ToString();
            string finyear = Grdoutward.DataKeys[e.Row.RowIndex].Values[4].ToString();

            string CustomerID = Grdoutward.DataKeys[e.Row.RowIndex].Values[1].ToString();
            string taxgroupID = Grdoutward.DataKeys[e.Row.RowIndex].Values[2].ToString();
            string CategoryID = Grdoutward.DataKeys[e.Row.RowIndex].Values[3].ToString();

            string sql = "select lname from ACC_ledmast where Lid=" + CustomerID;
           
            DataTable dt = du.getdata(sql);
            if (dt.Rows.Count > 0)
            {
                e.Row.Cells[2].Text = dt.Rows[0]["lname"].ToString();
            }


            string sql1 = "select SHORTNAME+'- '+ SUBCLASS as SUBCLASS from Ivr_dcgroup where ID=" + taxgroupID;
            dt = du.getdata(sql1);
            if (dt.Rows.Count > 0)
            {
                e.Row.Cells[3].Text = dt.Rows[0]["SUBCLASS"].ToString();
            }


            string Sql2 = "select CATEGORYNAME from Ivr_dccategory where Categorycode='"+ CategoryID +"'";
            dt = du.getdata(Sql2);
            if (dt.Rows.Count > 0)
            {
                e.Row.Cells[4].Text = dt.Rows[0]["CATEGORYNAME"].ToString();
            }
            ((HyperLink)e.Row.FindControl("hypdetails")).Attributes.Add("onclick", "Open_DCInward_Details('" + formateid + "','" + CustomerID + "','" + trnid + "','" + finyear + "')");
        }

    }

    private void EmptyTextBoxes(Control parent)
    {
        // Loop through all the controls on the page
        foreach (Control c in parent.Controls)
        {
            // Check and see if it's a textbox
            if ((c.GetType() == typeof(TextBox)))
            {
                // Since its a textbox clear out the text  
                ((TextBox)(c)).Text = "";
            }
            if ((c.GetType() == typeof(DropDownList)))
            {
                // Since its a textbox clear out the text  
                ((DropDownList)(c)).SelectedItem.Text = "";
            }
            // Now we need to call itself (recursive) because
            // all items (Panel, GroupBox, etc) is a container
            // so we need to check all containers for any
            // textboxes so we can clear them
            if (c.HasControls())
            {
                EmptyTextBoxes(c);
            }
        }
    }

    protected void Grdoutward_SelectedIndexChanged(object sender, EventArgs e)
    {
        string TFOID = Grdoutward.SelectedDataKey.Values[0].ToString();
        string VendCust_Lid = Grdoutward.SelectedDataKey.Values[1].ToString();
        string DCTAX_SUBCLASSID = Grdoutward.SelectedDataKey.Values[2].ToString();
        string DC_CATEGORYCODE = Grdoutward.SelectedDataKey.Values[3].ToString();
        string TRNID = Grdoutward.SelectedDataKey.Values[5].ToString();
        string FINYEAR = Grdoutward.SelectedDataKey.Values[4].ToString();

        //TFOID,VendCust_Lid,DCTAX_SUBCLASSID,DC_CATEGORYCODE,FINYEAR,TRNID"
         Response.Redirect("DCOutwardEdit.aspx?TFOID=" + TFOID + "&Vendor=" + VendCust_Lid +
          "&TAX=" + DCTAX_SUBCLASSID + "&CATEGORY=" + DC_CATEGORYCODE +
          "&TRNID=" + TRNID + "&FINYEAR=" + FINYEAR + "");
    }
}
